package me.zhengjie.rest;

import com.alibaba.fastjson.JSONObject;
import me.zhengjie.utils.Constants;
import me.zhengjie.utils.FileUtilLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class UploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @PostMapping("/upload")
    public ResponseEntity importData(MultipartFile file, HttpServletRequest req) throws IOException {
        String format = sdf.format(new Date());
//        String realPath = req.getServletContext().getRealPath("/upload") + format;
//        String realPath = Constants.BAK_DIR;
        String realPath = uploadFolder;

        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        file.transferTo(new File(folder, newName));
        String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/upload" + format + newName;
//        System.out.println(url);

        return new ResponseEntity("上传成功", HttpStatus.OK);
    }

    @GetMapping("/filenameinfold")
    public JSONObject getAllFileNameInFold(HttpServletRequest request) {

        List<JSONObject> fileList = FileUtilLocal.getAllFileNameInFold(uploadFolder + request.getParameter("ipaddr"));
        JSONObject responseJson = new JSONObject();
        responseJson.put("returnData",fileList);
        return responseJson;
    }
}